package com.simple.dispatcher.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import weibo4j.http.AccessToken;
import weibo4j.http.RequestToken;

import com.simple.dispatcher.service.WeiboOAuthService;
import com.simple.dispatcher.servlet.utils.RequestParamUtils;

@Controller
public class SinaOauthServlet extends HttpServlet {
		
	private final Log log = LogFactory.getLog(getClass());
	
	public static final String REQUEST_MAPPING = "/sinaoauth.do";
	
	@Autowired
	private WeiboOAuthService oauthService;
	
	@RequestMapping(REQUEST_MAPPING)
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String option = RequestParamUtils.getStringValue(req, "opt", "init");
		HttpSession session = req.getSession();
		if("init".equals(option)) {
			String callback_url = getCallbackURL(req.getRequestURL().toString());
			RequestToken requestToken = oauthService.getRequestToken(callback_url);
			if(requestToken != null) {
				session.setAttribute("requestToken", requestToken);
				String url = requestToken.getAuthorizationURL()+"&oauth_callback=" + callback_url;
				resp.sendRedirect(url);
			}
		} else if("getToken".equals(option)) {
			// 获得HTTP请求中的 oauth_verifier 参数 
			String verifier=req.getParameter("oauth_verifier"); 
			if(!StringUtils.isEmpty(verifier)) {
				RequestToken requestToken = (RequestToken)session.getAttribute("requestToken");
				if(requestToken != null){ 
					AccessToken accessToken = oauthService.gettAccessToken(requestToken,verifier);
					if(accessToken != null){
						session.setAttribute("accessToken", accessToken);
						resp.sendRedirect("pages/subscribe.jsp");
					}
				}
			}
		} else {
			log.debug("新浪微博授权失败!");
			resp.sendRedirect("welcome.do");
		}
	}
	
	/**
	 * 根据请求url生成callback_url
	 * @param path
	 * @return
	 */
	private String getCallbackURL(String path) {
        String url = "";
        if(!StringUtils.isEmpty(path)) {
            int index = path.indexOf(REQUEST_MAPPING);
            if(index != -1) {
                url = path.substring(0,index) + REQUEST_MAPPING + "?opt=getToken";
            }
        }
        return url;
    }

	public WeiboOAuthService getOauthService() {
		return oauthService;
	}

	public void setOauthService(WeiboOAuthService oauthService) {
		this.oauthService = oauthService;
	}
	
}
